<?php

namespace Laoha\Nav;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;


class LaohaNav extends Model
{
    protected $table = 'laoha_navs';
	//protected $fillable = ['name', 'title', 'parent_id', 'table_id'];


	
	use AdminBuilder, ModelTree {
        ModelTree::boot as treeBoot;
    }

    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct($root=0)
    {        
		if($root){
			static::addGlobalScope('avaiable',function(Builder $builder) use($root){
					$builder->where('root',$root);
			});
		}
        parent::__construct();
    }


    /**
     * determine if enable menu bind permission.
     *
     * @return bool
     */
    public function scopeRoot($query, $root)
    {
        return $query->where('root', $root);
    }

    /**
     * @return array
     */
    public function allNodes() : array
    {
        $connection = config('admin.database.connection') ?: config('database.default');
        $orderColumn = DB::connection($connection)->getQueryGrammar()->wrap($this->orderColumn);

        $byOrder = $orderColumn.' = 0,'.$orderColumn;

        return static::orderByRaw($byOrder)->get()->toArray();
    }


}
